from django.core.urlresolvers import resolve
from django.shortcuts import redirect
from django.contrib import messages
from blog.comment.forms import CommentForm
from blog.models import Comment, Post
from datetime import timedelta

class CommentMiddleware(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
        # If action = post_comment
        if request.POST.get('action', False) == 'post_comment':
            func, args, kwargs = resolve(request.path)
            post_id = kwargs['post_id']
            post  = Post.objects.get(pk = post_id)
            form = CommentForm(request.POST)
            # If there is no error(errors from user) then process the form
            if form.is_valid():
                comment = Comment(
                    name    = form.cleaned_data['name'],
                    email   = form.cleaned_data['email'],
                    content = form.cleaned_data['content'],
                    post    = post,
                )

                # Save the comment only in case of there is no similar since one minute
                if not post.has_similar_comments(comment, timedelta(minutes=1)):
                    comment.save()
                    # Success flash message
                    messages.success(request, 'Your comment has been saved successfully.')

                # If user has posted recently a comment on this post
                else:
                    # Error flash message
                    messages.error(request, 'You have commented on this post recently. Please wait a minute.')

                # Always redirect once the form is submitted and processed
                return redirect(post)

            # If there are some form errors(errors from user)
            else:
                request.rebounded_comment_form  = form
                # Error flash message
                messages.error(request, 'Please verify your comment.')

        # If action is not post comment
        else:
            return None